// 导入Promise
import {
	request
} from '../../request/index.js'


Page({
	data: {
		address: {},
		cart: [],
		allChecked: false,
		totalPrice: 0,
		totalNum: 0,
	},
	// 页面加载完毕
	onShow: function() {
		const address = wx.getStorageSync("address")
		const cart = wx.getStorageSync("cart") || []
		
		
		this.setData({address})
		this.setCart(cart)
	},
	handleChooseAddress() {
		wx.chooseAddress({
			success: (address) => {
				wx.setStorageSync("address", address)
				// console.log(address);
			}
		})
	},
	// 复选框事件改变
	handleItemChange(e) {
		// 获取ID
		const {
			id
		} = e.currentTarget.dataset
		// 获取商品列表
		let {
			cart
		} = this.data
		// 寻找ID
		let index = cart.findIndex(item => item.goods_id === id)
		// 选中了
		cart[index].checked = !cart[index].checked

		this.setCart(cart)

	},
	// 封装底部栏计算
	setCart(cart){
		// const allChecked = cart.length ? cart.every(item => item.checked) : false;
		let allChecked = true
		let totalPrice = 0
		let totalNum = 0
		cart.forEach(item => {
			if (item.checked) {
				totalPrice += item.num * item.goods_price
				totalNum += item.num
			}else{
				allChecked = false
			}
		})
		allChecked = cart.length!=0 ? allChecked : false ; 
		
		this.setData({
			cart,
			totalPrice,
			totalNum,
			allChecked
		})
		wx.setStorageSync("cart",cart)
	},
	// 全选和反选
	handleItemAllChange(){
		let {allChecked,cart} = this.data
		allChecked =! allChecked
		cart.forEach(item=>item.checked = allChecked)
		this.setCart(cart)
	} ,
	// 商品编辑
	oprationNum(e){
		const {id} = e.currentTarget.dataset
		const {opration} = e.currentTarget.dataset
		let {cart} = this.data
		const index = cart.findIndex(item => item.goods_id === id)
		// 弹窗提示
		if(cart[index].num === 1 && opration === -1){
			wx.showModal({
				title:"提示",
				content:"是否要删除该商品",
				success :res => {
					if(res.confirm){
						cart.splice(index,1)
						this.setCart(cart)
					}
				}
			})
		}else{
			cart[index].num += opration
			this.setCart(cart)
		}
	
	},
	// 结算功能
	handlePay(){
		const {address,totalNum,cart} = this.data
		// 空对象返回true
		/* 判断地址是否进入缓存 */
		if(!address.userName){
			wx.showToast({
				title:"请添加收货地址",
				icon:"none"
			})
			return;
		}
		
		/* 判断用户是否勾选了商品 */
		if(totalNum === 0){
			wx.showToast({
				title:"请添加商品或者勾选商品",
				icon:"none"
			})
			return;
		}
		//都检验好了，跳转页面

		wx.navigateTo({
			url:"/pages/pay/index"
		})
	}

})
